'use client';

import React, { useState, useEffect } from 'react';
import { useApi } from '@/hooks/use-api';
import { useSocket } from '@/hooks/use-socket';
import { useAuth } from '@/hooks/use-auth';
import { PermissionLevel } from '@/types/socket';
import { withMemo } from '@/components/hoc/with-memo';
import { ErrorBoundary } from '@/components/ui/error-boundary';
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogFooter,
  DialogTrigger 
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table';
import { 
  Select, 
  SelectContent, 
  SelectItem, 
  SelectTrigger, 
  SelectValue 
} from '@/components/ui/select';
import { toast } from '@/components/ui/use-toast';
import { 
  Shield, 
  UserPlus, 
  UserCog, 
  UserCheck, 
  Eye, 
  MessageSquare,
  Edit, 
  AlertCircle 
} from 'lucide-react';

// 用户权限类型
interface UserPermission {
  userId: string;
  userName: string;
  userEmail?: string;
  userImage?: string;
  role: string;
  permission: PermissionLevel;
  assignedAt: string;
  assignedBy: {
    id: string;
    name: string;
  };
}

// 权限级别选项
const permissionOptions: { value: PermissionLevel; label: string; icon: React.ReactNode }[] = [
  { value: 'owner', label: '所有者', icon: <Shield className="h-4 w-4" /> },
  { value: 'admin', label: '管理员', icon: <UserCog className="h-4 w-4" /> },
  { value: 'editor', label: '编辑者', icon: <Edit className="h-4 w-4" /> },
  { value: 'commenter', label: '评论者', icon: <MessageSquare className="h-4 w-4" /> },
  { value: 'viewer', label: '查看者', icon: <Eye className="h-4 w-4" /> },
];

// 获取权限描述
const getPermissionDescription = (permission: PermissionLevel): string => {
  switch (permission) {
    case 'owner':
      return '完全控制权限，包括删除项目和管理成员';
    case 'admin':
      return '管理权限，可以邀请和管理成员，但不能删除项目';
    case 'editor':
      return '编辑权限，可以创建和编辑所有文档';
    case 'commenter':
      return '评论权限，只能查看文档并添加评论或建议';
    case 'viewer':
      return '只读权限，只能查看文档，不能编辑或评论';
    default:
      return '未知权限';
  }
};

// 权限管理器属性
export interface PermissionManagerProps {
  projectId: string;
  onPermissionChange?: (data: {
    userId: string;
    permission: PermissionLevel;
  }) => Promise<void>;
}

// 权限管理器组件
function PermissionManagerComponent({
  projectId,
  onPermissionChange
}: PermissionManagerProps) {
  const { user } = useAuth();
  const [isOpen, setIsOpen] = useState(false);
  const [selectedUser, setSelectedUser] = useState<UserPermission | null>(null);
  const [newPermission, setNewPermission] = useState<PermissionLevel | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { 
    isConnected, 
    changePermission, 
    onPermissionChanged 
  } = useSocket();
  
  // 获取项目成员及权限
  const {
    data: members,
    setData: setMembers,
    isLoading,
    error,
    refetch,
    put: updatePermission
  } = useApi<UserPermission[]>(
    `/api/projects/${projectId}/permissions`,
    {
      autoFetch: true,
      useCache: true,
      cacheKey: `project_permissions_${projectId}`,
      showErrorNotification: true,
      errorNotificationTitle: '获取权限列表失败'
    }
  );
  
  // 当前用户的权限
  const currentUserPermission = members?.find(m => m.userId === user?.id)?.permission;
  
  // 判断是否有权限管理
  const canManagePermissions = 
    currentUserPermission === 'owner' || currentUserPermission === 'admin';
  
  // 监听权限变更
  useEffect(() => {
    if (!isConnected) return;
    
    const handlePermissionChanged = (data: any) => {
      if (data.projectId !== projectId) return;
      
      // 更新本地权限列表
      setMembers((prevMembers) => {
        if (!prevMembers) return prevMembers;
        
        return prevMembers.map(member => {
          if (member.userId === data.userId) {
            return {
              ...member,
              permission: data.newPermission,
              assignedAt: new Date().toISOString(),
              assignedBy: {
                id: data.changedBy.id,
                name: data.changedBy.name
              }
            };
          }
          return member;
        });
      });
      
      // 显示通知
      toast({
        title: "权限已更新",
        description: `${data.userName} 的权限已更改为 ${getPermissionName(data.newPermission)}`,
        duration: 3000
      });
    };
    
    const unsubscribe = onPermissionChanged(handlePermissionChanged);
    return unsubscribe;
  }, [isConnected, projectId, setMembers, onPermissionChanged]);
  
  // 打开权限编辑对话框
  const openPermissionDialog = (member: UserPermission) => {
    setSelectedUser(member);
    setNewPermission(member.permission);
    setIsOpen(true);
  };
  
  // 关闭权限编辑对话框
  const closePermissionDialog = () => {
    setIsOpen(false);
    setSelectedUser(null);
    setNewPermission(null);
  };
  
  // 获取权限名称
  const getPermissionName = (permission: PermissionLevel): string => {
    return permissionOptions.find(option => option.value === permission)?.label || '未知';
  };
  
  // 获取权限图标
  const getPermissionIcon = (permission: PermissionLevel): React.ReactNode => {
    return permissionOptions.find(option => option.value === permission)?.icon || <AlertCircle className="h-4 w-4" />;
  };
  
  // 更新权限
  const handleUpdatePermission = async () => {
    if (!selectedUser || !newPermission || newPermission === selectedUser.permission || isSubmitting) {
      return;
    }
    
    // 阻止变更所有者权限
    if (selectedUser.permission === 'owner') {
      toast({
        title: "操作被拒绝",
        description: "项目所有者的权限不能被更改",
        variant: "destructive"
      });
      return;
    }
    
    // 阻止提升他人为所有者
    if (newPermission === 'owner') {
      toast({
        title: "操作被拒绝",
        description: "无法将其他用户提升为项目所有者",
        variant: "destructive"
      });
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      // 调用API更新权限
      await updatePermission(
        {
          userId: selectedUser.userId,
          permission: newPermission
        },
        `/${selectedUser.userId}`
      );
      
      // 更新本地权限列表
      setMembers((prevMembers) => {
        if (!prevMembers) return prevMembers;
        
        return prevMembers.map(member => {
          if (member.userId === selectedUser.userId) {
            return {
              ...member,
              permission: newPermission,
              assignedAt: new Date().toISOString(),
              assignedBy: {
                id: user?.id || '',
                name: user?.name || '未知用户'
              }
            };
          }
          return member;
        });
      });
      
      // 触发自定义回调
      if (onPermissionChange) {
        await onPermissionChange({
          userId: selectedUser.userId,
          permission: newPermission
        });
      }
      
      // 发送实时通知
      if (isConnected && user) {
        changePermission({
          projectId,
          userId: selectedUser.userId,
          userName: selectedUser.userName,
          newPermission,
          changedBy: {
            id: user.id,
            name: user.name || '未知用户'
          },
          timestamp: Date.now()
        });
      }
      
      // 关闭对话框
      closePermissionDialog();
      
      // 显示成功通知
      toast({
        title: "权限已更新",
        description: `${selectedUser.userName} 的权限已更改为 ${getPermissionName(newPermission)}`,
        duration: 3000
      });
    } catch (error) {
      console.error('更新权限失败:', error);
      
      // 显示错误通知
      toast({
        title: "更新权限失败",
        description: error instanceof Error ? error.message : "发生未知错误",
        variant: "destructive"
      });
    } finally {
      setIsSubmitting(false);
    }
  };
  
  // 渲染权限列表
  const renderPermissionList = () => {
    if (isLoading) {
      return (
        <div className="flex items-center justify-center h-20">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
        </div>
      );
    }
    
    if (error || !members || members.length === 0) {
      return (
        <div className="text-center p-4">
          <p className="text-muted-foreground">暂无成员信息</p>
          <Button variant="outline" size="sm" className="mt-2" onClick={() => refetch()}>
            重试
          </Button>
        </div>
      );
    }
    
    return (
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-[200px]">成员</TableHead>
            <TableHead>权限</TableHead>
            <TableHead>授权时间</TableHead>
            <TableHead>授权人</TableHead>
            {canManagePermissions && <TableHead className="text-right">操作</TableHead>}
          </TableRow>
        </TableHeader>
        <TableBody>
          {members.map((member) => (
            <TableRow key={member.userId}>
              <TableCell className="font-medium">
                <div className="flex items-center">
                  {member.userImage && (
                    <img 
                      src={member.userImage} 
                      alt={member.userName} 
                      className="h-8 w-8 rounded-full mr-2"
                    />
                  )}
                  <div>
                    <div>{member.userName}</div>
                    {member.userEmail && (
                      <div className="text-xs text-muted-foreground">{member.userEmail}</div>
                    )}
                  </div>
                </div>
              </TableCell>
              <TableCell>
                <div className="flex items-center">
                  <div className="mr-2 text-muted-foreground">
                    {getPermissionIcon(member.permission)}
                  </div>
                  <div>
                    <div>{getPermissionName(member.permission)}</div>
                    <div className="text-xs text-muted-foreground">
                      {getPermissionDescription(member.permission)}
                    </div>
                  </div>
                </div>
              </TableCell>
              <TableCell>
                {new Date(member.assignedAt).toLocaleDateString()} {new Date(member.assignedAt).toLocaleTimeString()}
              </TableCell>
              <TableCell>
                {member.assignedBy.name}
              </TableCell>
              {canManagePermissions && (
                <TableCell className="text-right">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => openPermissionDialog(member)}
                    disabled={
                      member.permission === 'owner' || // 不能修改所有者
                      member.userId === user?.id // 不能修改自己
                    }
                  >
                    修改
                  </Button>
                </TableCell>
              )}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    );
  };
  
  return (
    <>
      <div>
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-medium">项目成员权限</h3>
          <Button variant="outline" size="sm" onClick={() => refetch()}>
            刷新
          </Button>
        </div>
        
        {renderPermissionList()}
      </div>
      
      {/* 权限编辑对话框 */}
      <Dialog open={isOpen} onOpenChange={setIsOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>修改权限</DialogTitle>
          </DialogHeader>
          
          {selectedUser && (
            <div className="space-y-4">
              <div className="flex items-center">
                {selectedUser.userImage && (
                  <img 
                    src={selectedUser.userImage} 
                    alt={selectedUser.userName} 
                    className="h-10 w-10 rounded-full mr-3"
                  />
                )}
                <div>
                  <div className="font-medium">{selectedUser.userName}</div>
                  {selectedUser.userEmail && (
                    <div className="text-sm text-muted-foreground">{selectedUser.userEmail}</div>
                  )}
                </div>
              </div>
              
              <div className="space-y-2">
                <label className="text-sm font-medium">当前权限</label>
                <div className="flex items-center rounded-md border p-2">
                  <div className="mr-2 text-muted-foreground">
                    {getPermissionIcon(selectedUser.permission)}
                  </div>
                  <div>
                    <div>{getPermissionName(selectedUser.permission)}</div>
                    <div className="text-xs text-muted-foreground">
                      {getPermissionDescription(selectedUser.permission)}
                    </div>
                  </div>
                </div>
              </div>
              
              <div className="space-y-2">
                <label className="text-sm font-medium">新权限</label>
                <Select
                  value={newPermission || undefined}
                  onValueChange={(value: PermissionLevel) => setNewPermission(value)}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择权限" />
                  </SelectTrigger>
                  <SelectContent>
                    {permissionOptions
                      .filter(option => option.value !== 'owner') // 过滤掉所有者选项
                      .map(option => (
                        <SelectItem key={option.value} value={option.value}>
                          <div className="flex items-center">
                            <div className="mr-2">{option.icon}</div>
                            <span>{option.label}</span>
                          </div>
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
                
                {newPermission && (
                  <div className="text-xs text-muted-foreground mt-1">
                    {getPermissionDescription(newPermission)}
                  </div>
                )}
              </div>
            </div>
          )}
          
          <DialogFooter>
            <Button variant="outline" onClick={closePermissionDialog}>
              取消
            </Button>
            <Button 
              onClick={handleUpdatePermission}
              disabled={
                isSubmitting || 
                !newPermission || 
                (selectedUser && newPermission === selectedUser.permission)
              }
            >
              {isSubmitting ? '更新中...' : '更新权限'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}

// 使用记忆化HOC优化渲染性能
const MemoizedPermissionManager = withMemo(PermissionManagerComponent);

// 带错误边界的权限管理器组件
export function PermissionManager(props: PermissionManagerProps) {
  return (
    <ErrorBoundary>
      <MemoizedPermissionManager {...props} />
    </ErrorBoundary>
  );
} 